<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/8/2
 * Time: 下午3:06
 */

namespace backend\controllers;

use common\models\ar\RealName;
use common\models\ar\User;
use common\models\ar\UserBrokers;
use common\models\ar\UserTrade;
use common\models\Common;
use common\models\TraderDao;
use common\models\UserDao;
use common\models\UserInfoDetailDao;
use common\models\ar\UserMoney;
use common\models\ar\ChangeCache;
use common\models\ar\HistoryUserInfoAlter;
class TraderController extends BackendController
{
    /**
     * 交易客户列表
     */
    public function actionLists()
    {
        $req = \Yii::$app->request;
        $isRender = $req->get('isRender', 1);//1为搜索页面，2为异步获取代理记录
        $userModel = UserBrokers::findOne(\Yii::$app->user->identity->id);
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);
        $isLast = $levelInfo['is_trade'] == 1 ? true : false;
        $pageNo = (int)$req->get('pageNo', 1);
        $pageSize = \Yii::$app->params['pageSize'];
        if ($isRender == 1) {
            $return = [
                'pageNo' => $pageNo,
                'pageTotal' => 0,
                'is_last' => $isLast,
            ];
            return $this->renderPartial('lists', $return);
        }
        $regType = (int)$req->get('register_type', -1);
        $clientSN = trim($req->get('clientSN', ''));
        $pClientSN = trim($req->get('p_clientSN', ''));
        $start_str = trim($req->get('time_start', ''));
        $end_str = trim($req->get('time_end', ''));

        $timeStart = $start_str != '' ? strtotime($start_str) : 0;
        $timeEnd = $end_str != '' ? strtotime($end_str) : 0;
        $uid = -1;
        if ($clientSN != '') {
            if (is_numeric($clientSN)) {
                //数字类型，以客户编号搜索
                $where['clientSN'] = $clientSN;
            } else {
                //非数字类型，以姓名搜索
                $where['clientSN'] = $clientSN;
            }
            // var_dump($where);
            // exit();
            $tmp = User::find()->where(['loginName'=>$where['clientSN']])->one();
            if (!$tmp) {
                $uid = 0;
            } else {
                $uid = $tmp->userID;
            }
        }
        if ($pClientSN) {
            $where = [];
            if (is_numeric($pClientSN)) {
                if ($pClientSN != $userModel->clientSN) {
                    $where['clientSN'] = $pClientSN;
                }
            } else {
                if ($pClientSN != $userModel->alias) {
                    $where['alias'] = $pClientSN;
                }
            }
            if (!empty($where)) {
                $tmp = User::find()->where($userModel['level'])->one();
                if (!$tmp) {
                    $pid = 0;
                    $pLevel = 0;
                } else {
                    $pid = $tmp->id;
                    $pLevel = $tmp->level;
                }
            } else {
                $pid = $userModel->id;
                $pLevel = $userModel->level;
            }
        } else {
            $pid = $userModel->id;
            $pLevel = $userModel->level;
        }
        //直接返回
        if ($uid == 0 || $pid == 0) {
            $return = [
                'pageNo' => $pageNo,
                'pageTotal' => 0,
                'lists' => [],
                'is_last' => $isLast,
            ];
        } else {
            $res = UserDao::traderLists(
                $regType,
                $pid,
                $pLevel,
                $uid,
                $timeStart,
                $timeEnd,
                $pageNo,
                $pageSize
            );

            $return = [
                'pageNo' => $pageNo,
                'pageTotal' => ceil($res['total'] / $pageSize),
                'lists' => $res['lists'],
                'is_last' => $isLast,
            ];
        }

        exit(json_encode($return));
    }

    /**
     * 添加客户的表单
     *
     * @return string
     */
    public function actionAddForm()
    {
        $uid = \Yii::$app->user->identity->id;
        $level = \Yii::$app->user->identity->level;
        $levelInfo = Common::getLevelsInfo($level);
        if ($levelInfo['is_last'] != 1) {
            exit('营业部级别代理才能执行此操作');
        }

        //手续费模板库
        // $templates = Templates::find()
        //     ->select(['id', 'title', 'is_default'])
        //     ->where([
        //         'uid' => $uid,
        //         'status' => 1
        //     ])
        //     ->orderBy('id DESC')->asArray()->all();
        return $this->renderPartial('add-form');
         // return $this->renderPartial('add-form', [
         //     'templates' => $templates
         // ]);
    }

    /**
     * 添加客户
     */
    public function actionAddSubmit()
    {
        $uidOperate = \Yii::$app->user->identity->id;
//        $levelInfo = Common::getLevelsInfo($level);
        $A_name=UserBrokers::findOne(['id'=>$uidOperate]);
        // if ($obj->login_flag == 0) {
        //     $code = 1001;
        //     $msg = "您的账户未激活，请至 `账户激活` &gt; `创建返佣账户` 中完成创建操作";
        //     exit(json_encode(['code' => $code, 'msg' => $msg]));
        // }
        $req = \Yii::$app->request;
        $password = trim($req->post('password', ''));
        $passwordConfirm = trim($req->post('password_confirm', ''));
        $alias = strip_tags(trim($req->post('alias', '')));
        $cellPhone=$req->post('tel','');
        $time=date("Y-m-d H:i:s");
        if (strlen($password) < 6) {
            $code = 1003;
            $msg = '密码长度不能小于6位';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($password != $passwordConfirm) {
            $code = 1004;
            $msg = '确认密码检验失败：两次密码不一致';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        if (strlen($A_name['level'])<2) {
            $num = str_pad($A_name['level'], 2, "0", STR_PAD_LEFT);
        }else{
            $num=$A_name['level'];
        }
//        $tel=User::findOne(['cellPhone'=>$cellPhone]);
//        if ($tel) {
//            $code = 1005;
//            $msg = '手机号码已存在！';
//            exit(json_encode(['code' => $code, 'msg' => $msg]));
//        }
//       $check = Common::dataCheck($tel, [
//           'type' => 3,
//           'detail' => [
//               'pattern' => '/^1[34578][0-9]{9}$/',
//               'info' => '手机号码不正确'
//           ],
//       ]);


        $clientSN ='12464';
        $clientSN ="8{$num}{$clientSN}";
        $clientLike = "8{$num}%";
        $userTmp = "SELECT `loginName` FROM `user` WHERE loginName like '".$clientLike."' ORDER BY `loginName` DESC LIMIT 1";
        $userTmp = User::findBySql($userTmp)->one();
        if($userTmp)
        {
            $clientSN=(string)($userTmp['loginName']+1);
        }
//       $time=date("Y-m-d H:i:s");
//        $UserBrokers=new UserBrokers();
//        $UserBrokers->loginName=$clientSN;
//        $UserBrokers->loginPsw =$password;
//        $UserBrokers->accountName =$alias;
//        $UserBrokers->level = $A_name['level']+1;
//        $UserBrokers->upperLevelId=$A_name['id'];
//        $UserBrokers->templateId ='';
//        $UserBrokers->addDate = $time;
//        $UserBrokers->save();

        $users=new User();
        $users->loginName = $clientSN;
        $users->loginpsw =$password;
        $users->accountName = $alias;
        $users->userType = 1001;
        $users->address ="";
        $users->cellPhone =$cellPhone;
        $users->RegisterDate = $time;
        $users->line_waring = 20;
        $users-> line_LimitOpen = 10;
        $users-> line_ForceClose = 10;
        $users-> hedgeStrategy = 5;
        $users->limit_openorder = 0;
        $users->agentID=$A_name['id'];
        $users-> login_flag= 2;
        $users->templatePtId=0;
        $users->save(false);
        //查找id并将ID写入到change_caches
        $UserIDs=User::find()->where(['loginName'=>$clientSN])->one();
        $Changecaches = new Changecache;
        $Changecaches->userid=$UserIDs['userID'];
        $Changecaches->change_type=1;
        $Changecaches->save();
        //ID写入到user_money,初始化资金表
        $userMoney= new UserMoney();
        $userMoney->userID=$UserIDs['userID'];
        $userMoney->totalMoney=0;
        $userMoney->userDeposit=0;
        $userMoney->equip=0;
        $userMoney->save();
        if (!$users->save(false)) {
            $code = 0;
            $msg = "创建失败";
        } else {
            $code = 1;
            $msg = "创建成功";

            //登录的账户名保存到cookie中
            setcookie("login_clientSN", $clientSN, time() + 7 * 24 * 3600, '/');
            //主动登录一次
        }
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 修改用户信息表单
     *
     * @return string
     */
    public function actionSetForm()
    {

        $uid = \Yii::$app->request->get('userID', 0);
        $uids=RealName::findOne(['userID'=>$uid]);

        if ($uids['level']==1) {
            $base = User::find()->where(['userID' => $uid])->asArray()->one();
            $level=1;
        }else{
            $base = UserBrokers::find()->where(['id' => $uid])->asArray()->one();
            $level=2;
        }
        if (!$base) {
            exit("账户不存在");
        }
        //是否是直接上级
        if ($uids['level']==1) {
        $isParent = false;
        if (\Yii::$app->user->identity->id == $base['agentID']) {
            $isParent = true;
        }
        $uid = $base['userID'];
        $userInfo = User::find()->where(['userID' => $uid])->one();

        //资金信息
        $moneyInfo = [];
        $tmp = TraderDao::moneyInfo([$uid]);
        if (isset($tmp[$uid])) {
            $moneyInfo = $tmp[$uid];
        }
        }else{
            $userInfo = UserBrokers::find()->where(['id' => $uid])->one();
            $moneyInfo=0;
        }
        //实名信息
        $tmp = RealName::findOne($uid);
        if (!$tmp || $tmp->status != 1) {
            $realNameInfo = [];
        } else {
            $realNameInfo = UserInfoDetailDao::info($uid, 6, 0);
        }
        // var_dump($userInfo);
        // var_dump($moneyInfo);
        // var_dump($realNameInfo);
        // exit();
            return $this->renderPartial('set-form', [
            'userInfo' => $userInfo,
            'moneyInfo' => $moneyInfo,
            'realNameInfo' => $realNameInfo,
            'level'=>$level
        ]);
    }

    /**
     * 修改别名
     */
    public function actionChangeAlias()
    {
        $req = \Yii::$app->request;
        $uidOperate = \Yii::$app->user->identity->id;
        $levelInfo = Common::getLevelsInfo(\Yii::$app->user->identity->level);

        $uid = $req->get('uid', 0);
        $obj = User::findOne(['userID'=>$uid]);
        if ($levelInfo['is_first'] != 1 && (!$obj || $obj->pid != $uidOperate)) {
            $code = 1001;
            $msg = "权限不足";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        $alias = strip_tags(trim($req->get('alias', '')));
        if ($alias == $obj->accountName) {
            $code = 1002;
            $msg = '姓名未变更，请输入需要修改的姓名';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $len = mb_strlen($alias);
        if ($len < 2) {
            $code = 1003;
            $msg = '请输入客户的姓名';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        $obj->accountName = $alias;
        $bool = $obj->save(false);
        if ($bool) {
            $history = new HistoryUserInfoAlter();
            $history->attributes = [
                'uid_operate' => $uidOperate,
                'uid' => $uid,
                'type' => 7,
                'create_time' => time(),
                'ip' => $req->userIP,
                'ua' => $req->userAgent,
                'remark' => json_encode(['alias' => $alias])
            ];
            $bool = $history->save(false);
        }

        if ($bool) {
            //交易数据库也要修改
            $sql = "UPDATE `user` SET `accountName` = :alias WHERE `userID` = :uid";
            $db = \Yii::$app->db;
            $db->createCommand($sql, [':alias' => $alias, ':uid' => $uid])->execute();
        }
        $name=new ChangeCache();
        $name->userid=$uid;
        $name->change_type=1;
        $name->save(false);
        exit(json_encode(['code' => $bool ? 1 : 0, 'msg' => $bool ? '修改成功' : '修改失败']));
    }

    /**
     * 修改密码
     */
    public function actionChangePwd1()
    {
        $req = \Yii::$app->request;
        $uid = $req->get('uid', 0);
        $obj = User::findOne($uid);
        $pwd = strip_tags(trim($req->get('password', '')));
        if ($pwd == $obj->loginpsw) {
            $code = 1002;
            $msg = '你输入的密码和原密码一样！';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        $len = mb_strlen($req->get('password'));
        if ($len < 2) {
            $code = 1003;
            $msg = '请输入正确的密码';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        $obj->loginpsw = $pwd;
        $bool = $obj->save(false);
        if ($bool) {
            $history = new HistoryUserInfoAlter();
            $history->attributes = [
                'uid' => $uid,
                'type' => 7,
                'create_time' => time(),
                'ip' => $req->userIP,
                'ua' => $req->userAgent,
                'remark' => json_encode(['password' => $pwd])
            ];
            $bool = $history->save();
        }

        if ($bool) {
            //交易数据库也要修改
            $sql = "UPDATE `user` SET `loginpsw` = :password WHERE `userID` = :uid";
            $db = \Yii::$app->db;
            $db->createCommand($sql, [':password' => $pwd, ':uid' => $uid])->execute();
        }
        $pwd1=new ChangeCache();
        $pwd1->userid=$uid;
        $pwd1->change_type=1;
        $pwd1->save(false);
        exit(json_encode(['code' => $bool ? 1 : 0, 'msg' => $bool ? '修改成功' : '修改失败']));
    }
}
